/*
 *    Copyright (c) 2018-2025, cloud All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: cloud
 */

package com.fuyao.cloud.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fuyao.cloud.common.core.constant.CommonConstants;
import com.fuyao.cloud.common.core.constant.SecurityConstants;
import com.fuyao.cloud.common.core.util.R;
import com.fuyao.cloud.gateway.LicenseVerifyProperties;
import com.fuyao.license.checker.LicenseVerifyManager;
import com.fuyao.license.checker.LicenseVerifyResult;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

import java.nio.file.Files;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.addOriginalRequestUrl;

/**
 * @author cloud
 * @date 2018/10/8
 * <p>
 * 全局拦截器，作用所有的微服务
 * <p>
 * 1. 对请求头中参数进行处理 from 参数进行清洗 2. 重写StripPrefix = 1,支持全局
 * <p>
 * 支持swagger添加X-Forwarded-Prefix header （F SR2 已经支持，不需要自己维护）
 */
@Slf4j
@Component
@AllArgsConstructor
public class CloudRequestGlobalFilter implements GlobalFilter, Ordered {

    private final LicenseVerifyProperties properties;

    private final ObjectMapper objectMapper;

    private final AtomicInteger atomicInteger = new AtomicInteger();

    private static boolean isLicenseValid = true;

    /**
     * Process the Web request and (optionally) delegate to the next {@code WebFilter}
     * through the given {@link GatewayFilterChain}.
     *
     * @param exchange the current server exchange
     * @param chain    provides a way to delegate to the next filter
     * @return {@code Mono<Void>} to indicate when request processing is complete
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        if (log.isDebugEnabled()) {
            log.debug("=============================请求头开始=============================");
            exchange.getRequest().getHeaders().forEach((key, values) -> log.debug(key + ":" + String.join(",", values)));
            log.debug("=============================请求头结束=============================");
        }

        return Mono.fromCallable(() -> {
                    // 每 10 次请求检查一次
                    if (atomicInteger.get() == 0 || atomicInteger.get() > 10) {
                        atomicInteger.getAndSet(0);
                        LicenseVerifyManager licenseVerifyManager = new LicenseVerifyManager();
                        // 1、校验证书是否有效
                        LicenseVerifyResult verifyResult = licenseVerifyManager.verify(
                                properties.getVerifyParam(),
                                Files.newInputStream(ResourceUtils.getFile(properties.getPublicKeysStorePath()).toPath())
                        );
                        isLicenseValid = verifyResult.getResult();
                    }
                    if (!isLicenseValid) {
                        return false;
                    }
                    atomicInteger.getAndIncrement();
                    return true;
                }).subscribeOn(Schedulers.immediate())
                .flatMap(validate -> {

                    if (!validate) {
                        ServerHttpResponse response = exchange.getResponse();
                        response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
                        R<Object> r = R.failed("证书无效,请联系管理员");
                        r.setCode(-20000);
                        try {
                            return response.writeWith(Mono.just(response.bufferFactory().wrap(objectMapper.writeValueAsBytes(r))));
                        } catch (JsonProcessingException e) {
                            return Mono.error(e);
                        }
                    }

                    // 处理请求头
                    ServerHttpRequest request = exchange.getRequest().mutate().headers(httpHeaders -> {
                        // 清洗请求头中 from 参数
                        httpHeaders.remove(SecurityConstants.FROM);
                        httpHeaders.put(CommonConstants.REQUEST_START_TIME, Collections.singletonList(String.valueOf(System.currentTimeMillis())));
                    }).build();

                    // 重写 StripPrefix
                    addOriginalRequestUrl(exchange, request.getURI());
                    String rawPath = request.getURI().getRawPath();
                    String newPath = "/" + Arrays.stream(StringUtils.tokenizeToStringArray(rawPath, "/")).skip(1).collect(Collectors.joining("/"));
                    ServerHttpRequest newRequest = request.mutate().path(newPath).build();
                    exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, newRequest.getURI());

                    if (log.isDebugEnabled()) {
                        log.debug("route to -> " + newRequest.getURI());
                    }

                    return chain.filter(exchange.mutate().request(newRequest).build()).then(Mono.fromRunnable(() -> {
                        if (log.isDebugEnabled()) {
                            log.debug("=============================响应头开始=============================");
                            exchange.getResponse().getHeaders().forEach((key, values) -> log.debug(key + ":" + String.join(",", values)));
                            log.debug("=============================响应头结束=============================");
                            log.debug("");
                        }
                    }));
                });
    }

    @Override
    public int getOrder() {
        return -1000;
    }

}
